package com.ruoyi.attachedRecord.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

import com.ruoyi.attachedData.domain.AttachedData;
import com.ruoyi.attachedData.service.IAttachedDataService;
import com.ruoyi.commission.domain.Commission;
import com.ruoyi.commission.service.ICommissionService;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.engineering.domain.Engineering;
import com.ruoyi.engineering.service.IEngineeringService;
import com.ruoyi.instrument.domain.Instrument;
import com.ruoyi.instrument.service.IInstrumentService;
import com.ruoyi.notice.domain.Notice;
import com.ruoyi.notice.service.INoticeService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.task.domain.Task;
import com.ruoyi.task.service.ITaskService;
import com.ruoyi.weeklyReport.domain.WeeklyReport;
import com.ruoyi.weeklyReport.service.IWeeklyReportService;
import com.ruoyi.workload.domain.Workload;
import com.ruoyi.workload.mapper.WorkloadMapper;
import org.apache.poi.hpsf.Decimal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.attachedRecord.mapper.AttachedRecordMapper;
import com.ruoyi.attachedRecord.domain.AttachedRecord;
import com.ruoyi.attachedRecord.service.IAttachedRecordService;

import javax.annotation.Resource;

import static java.util.Calendar.*;

/**
 * 检测记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-19
 */
@Service
public class AttachedRecordServiceImpl implements IAttachedRecordService {
    @Autowired
    private AttachedRecordMapper attachedRecordMapper;

    @Resource
    private IAttachedDataService attachedDataService;

    @Resource
    private IInstrumentService instrumentService;

    @Autowired
    private ICommissionService commissionService;

    @Autowired
    private IEngineeringService engineeringService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Resource
    private WorkloadMapper workloadMapper;

    @Autowired
    private IAttachedRecordService attachedRecordService;

    @Autowired
    private ITaskService taskService;

    @Autowired
    private IWeeklyReportService weeklyReportService;

    @Autowired
    private INoticeService noticeService;

    /**
     * 查询检测记录
     *
     * @param id 检测记录主键
     * @return 检测记录
     */
    @Override
    public AttachedRecord selectAttachedRecordById(Long id) {
        return attachedRecordMapper.selectAttachedRecordById(id);
    }

    /**
     * 查询检测记录列表
     *
     * @param attachedRecord 检测记录
     * @return 检测记录
     */
    @Override
    public List<AttachedRecord> selectAttachedRecordList(AttachedRecord attachedRecord) {
        List<AttachedRecord> attList = attachedRecordMapper.selectAttachedRecordList(attachedRecord);
        if (!attList.isEmpty()) {
            for (AttachedRecord att : attList) {
                if (StringUtils.isNotEmpty(att.getTestInstrument())) {
                    String[] fruits = att.getTestInstrument().split(",");
                    List<String> fruitsList = new ArrayList<>();
                    for (String fruit : fruits) {
                        Instrument ii = instrumentService.selectInstrumentById(Long.parseLong(fruit));
                        if(ii != null && StringUtils.isNotEmpty(ii.getInstrumentName())){
                            fruitsList.add(ii.getInstrumentName());
                        }
                    }
                    if(StringUtils.isNotEmpty(fruitsList)){
                        att.setTestInstrument(String.join(",",fruitsList));
                    }
                }
            }
        }
        return attList;
    }

    @Override
    public  Integer selectAttachedRecordListForSum(AttachedRecord attachedRecord){
        List<AttachedRecord> attachedRecordList = attachedRecordService.selectAttachedRecordList(attachedRecord);
        Integer allAttachedRecordNum = 0;
        if(attachedRecordList.size() > 0) {
            for (AttachedRecord item : attachedRecordList) {
                Integer testNumber = 0;
                if(item.getTestNumber() == null || item.getTestNumber().isEmpty()){
                    testNumber = 0;
                }else{
                    testNumber = Integer.parseInt(item.getTestNumber());
                }
                allAttachedRecordNum += testNumber;
            }
        }
        return allAttachedRecordNum;
    }

    /**
     * 新增检测记录
     *
     * @param attachedRecord 检测记录
     * @return 结果
     */
    @Override
    public int insertAttachedRecord(AttachedRecord attachedRecord) {
        attachedRecord.setCreateTime(DateUtils.getNowDate());
        Engineering engineeringOne2 = engineeringService.selectEngineeringById(attachedRecord.getEngineeringId());
        attachedRecord.setEnterpriseId(engineeringOne2.getEnterpriseId());
        Integer isAcr = attachedRecordMapper.insertAttachedRecord(attachedRecord);
        //原始编号
        Long id = attachedRecord.getId();
        AttachedData attachedDataOne = attachedDataService.selectAttachedDataById(attachedRecord.getAttachedDataId());

        //生成报告编号  工程编号➕JL➕分类编码➕年份后两位➕序号
        Calendar calendar = getInstance();
        int year = calendar.get(YEAR); // 获取当前年份

        Long commissionId = attachedRecord.getCommissionId();
        Commission commissionOne = commissionService.selectCommissionById(commissionId);

        Engineering engineeringOne = engineeringService.selectEngineeringById(commissionOne.getEngineeringId());

        //分类编码
        String fenleiNumber = "";
        List<SysDictData> sysDictDatalist = dictDataService.selectDictDataByDictType("detection_item_scene");
        for (SysDictData sysDictData : sysDictDatalist) {
            if (sysDictData.getDictLabel().equals(attachedDataOne.getTestMethod())) {
                fenleiNumber = sysDictData.getDictValue();
            }
        }

        String year2 = String.valueOf(year);
        String lastTwoChars = year2.substring(year2.length() - 2);
        String id_str = "";
        if(id < 10L){
            id_str = "000"+String.valueOf(id);
        }else if(id < 100L && id >= 10L){
            id_str = "00"+String.valueOf(id);
        }else if(id < 1000L && id >= 100L){
            id_str = "0"+String.valueOf(id);
        }
        else {
            id_str = String.valueOf(id);
        }
        String number = engineeringOne.getEngineeringNumber()+"JL"+ fenleiNumber + lastTwoChars + id_str;

        AttachedRecord attachedRecord2 = new AttachedRecord();
        attachedRecord2.setId(id);
        attachedRecord2.setOriginalNumber(number);
        attachedRecordMapper.updateAttachedRecord(attachedRecord2);

        //录入数据的数量 大于等于 试验项目的数量 就改变状态
        AttachedRecord attachedRecord3 = new AttachedRecord();
        attachedRecord3.setAttachedDataId(attachedRecord.getAttachedDataId());
        Integer ar_num = attachedRecordService.selectAttachedRecordListForSum(attachedRecord3);
        if(ar_num >= Integer.valueOf(attachedDataOne.getAmount())){
            AttachedData attachedData = new AttachedData();
            attachedData.setId(attachedRecord.getAttachedDataId());
            attachedData.setIsDone(2L);
            attachedDataService.updateAttachedData(attachedData);

            //完成任务 更新之前任务
            Task task1 = new Task();
            task1.setTaskType("检测数据录入");
            task1.setCommissionId(attachedData.getCommissionId());
            task1.setChargePerson(attachedDataOne.getChargePerson());
            List<Task> taskList = taskService.selectTaskList(task1);
            if(taskList.size() > 0){
                task1.setId(taskList.get(0).getId());
                task1.setStatus("1");
                task1.setExecuteTime(DateUtils.getNowDate());
                taskService.updateTask(task1);
            }

            //消息 报告上传 负责人
            Notice notice = new Notice();
            notice.setCommissionId(commissionOne.getId());
            notice.setEngineeringId(commissionOne.getEngineeringId());
            notice.setNoticType("报告上传");
            notice.setNoticContent("请及时上传"+commissionOne.getEngineeringName()+"的委托单"+commissionOne.getNumber()+" "+attachedDataOne.getTestMethod()+"检测报告！");
            notice.setUserId(attachedDataOne.getChargePerson());
            noticeService.insertNotice(notice);
        }

        //进度管理那边 统计 完成数量，累计完成数量 完成工作量
        WeeklyReport weeklyReport = new WeeklyReport();
        weeklyReport.setCommissionId(attachedDataOne.getCommissionId());
        weeklyReport.setEngineeringId(attachedDataOne.getEngineeringId());
        weeklyReport.setAttachedDataId(attachedDataOne.getId());
        List<WeeklyReport> weeklyReportList = weeklyReportService.selectWeeklyReportList(weeklyReport);
        if(weeklyReportList.size() > 0){
            //有进度 统计 完成数量，累计完成数量 完成工作量
            Long total = weeklyReportList.get(0).getTotal();//工程总量
            Long weeklyReporId = weeklyReportList.get(0).getId();
            WeeklyReport weeklyReport2 = new WeeklyReport();
            weeklyReport2.setId(weeklyReporId);
            weeklyReport2.setDoneTotalNum(Long.valueOf(ar_num));//累计完成数量
            Double chuzhi = (double) ar_num / total*100;

            weeklyReport2.setDoneTotal(String.valueOf(chuzhi)+"%");//完成工作量(累计完成数量/工作总量)

            // 获取当前日期
            LocalDate today = LocalDate.now();

            // 计算当前星期的星期四
            LocalDate thursdayOfCurrentWeek = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.THURSDAY));
            Date thursday = Date.from(thursdayOfCurrentWeek.atStartOfDay(ZoneId.systemDefault()).toInstant());
            // 输出结果
            System.out.println("当前星期的星期四的日期是: " + thursdayOfCurrentWeek);

            AttachedRecord attachedRecord4 = new AttachedRecord();
            attachedRecord4.setAttachedDataId(attachedRecord.getAttachedDataId());
            attachedRecord4.setThursday(thursday);
            Integer doneNum = attachedRecordService.selectAttachedRecordListForSum(attachedRecord4);
            weeklyReport2.setDoneNum(Long.valueOf(doneNum));//完成数量

            weeklyReportService.updateWeeklyReport(weeklyReport2);

        }
        return isAcr;
    }

    /**
     * 修改检测记录
     *
     * @param attachedRecord 检测记录
     * @return 结果
     */
    @Override
    public int updateAttachedRecord(AttachedRecord attachedRecord) {
        attachedRecord.setUpdateTime(DateUtils.getNowDate());
        Integer isatt = attachedRecordMapper.updateAttachedRecord(attachedRecord);

        AttachedRecord attachedRecordOne = attachedRecordMapper.selectAttachedRecordById(attachedRecord.getId());
        System.out.println("atrOne");
        System.out.println(attachedRecordOne);

        //改变 上一级 isDone状态
        Integer completionNumber = 0;
        AttachedRecord attachedRecord2 = new AttachedRecord();
        attachedRecord2.setCommissionId(attachedRecordOne.getCommissionId());
        attachedRecord2.setAttachedDataId(attachedRecordOne.getAttachedDataId());
        List<AttachedRecord> attachedRecordList = attachedRecordMapper.selectAttachedRecordList(attachedRecord2);
        if (!attachedRecordList.isEmpty()) {
            for (AttachedRecord attachedData2 : attachedRecordList) {
                if(StringUtils.isNotEmpty(attachedData2.getTestNumber())){
                    completionNumber += Integer.parseInt(attachedData2.getTestNumber());
                }
            }
        }

        //AttachedData attOne = attachedDataService.selectAttachedDataById(attachedRecordOne.getAttachedDataId());
        AttachedData attachedDataOne = attachedDataService.selectAttachedDataById(attachedRecordOne.getAttachedDataId());
        Commission commissionOne = commissionService.selectCommissionById(attachedRecordOne.getCommissionId());

        System.out.println(commissionOne);

        AttachedData att = new AttachedData();
        //卡片总数 大于 试验项目数量 改变 isDone
        if (completionNumber >= Integer.parseInt(attachedDataOne.getAmount())) {
            att.setId(attachedDataOne.getId());
            att.setIsDone(2L);
            //att.setStatus(2L);
            attachedDataService.updateAttachedData(att);


            //完成任务 更新之前任务
            Task task1 = new Task();
            task1.setTaskType("检测数据录入");
            task1.setCommissionId(attachedDataOne.getCommissionId());
            task1.setChargePerson(attachedDataOne.getChargePerson());
            List<Task> taskList = taskService.selectTaskList(task1);
            if(taskList.size() > 0){
                task1.setId(taskList.get(0).getId());
                task1.setStatus("1");
                task1.setExecuteTime(DateUtils.getNowDate());
                taskService.updateTask(task1);
            }

            //消息 报告上传 负责人
            Notice notice = new Notice();
            notice.setCommissionId(attachedDataOne.getCommissionId());
            notice.setEngineeringId(commissionOne.getEngineeringId());
            notice.setNoticType("报告上传");
            notice.setNoticContent("请及时上传"+commissionOne.getEngineeringName()+"的委托单"+commissionOne.getNumber()+" "+attachedDataOne.getTestMethod()+"检测报告！");
            notice.setUserId(attachedDataOne.getChargePerson());
            noticeService.insertNotice(notice);


        }
        return isatt;
    }

    /**
     * 批量删除检测记录
     *
     * @param ids 需要删除的检测记录主键
     * @return 结果
     */
    @Override
    public int deleteAttachedRecordByIds(Long[] ids) {
        return attachedRecordMapper.deleteAttachedRecordByIds(ids);
    }


    /**
     * 批量逻辑删除检测记录
     *
     * @param ids 需要删除的检测记录主键
     * @return 结果
     */
    @Override
    public int logicDeleteAttachedRecord(Long[] ids, String delType, Long delUser) {
        return attachedRecordMapper.logicDeleteAttachedRecord(ids, delType, delUser);
    }

    /**
     * 删除检测记录信息
     *
     * @param id 检测记录主键
     * @return 结果
     */
    @Override
    public int deleteAttachedRecordById(Long id) {
        return attachedRecordMapper.deleteAttachedRecordById(id);
    }
}
